#include "TextDocument.h"
#include "Object/NewObject.h"
#include "File/FileUtils.h"
#include "Framework/Editor.h"


void RTextDocument::SetFilePath(const SPath &InPath)
{
    FilePath=InPath;

    InitPieceTable();

}

TSharedObjectPtr<RTextDocument> RTextDocument::Create(const SPath & InPath)
{
    TSharedObjectPtr<RTextDocument> NewDocument = NewObject<RTextDocument>(REditor::Get()->GetRootOfModel());
    NewDocument->SetFilePath(InPath);
    return NewDocument;
}

bool RTextDocument::HasUnsavedData() const
{
    return PieceTable.IsDocumentChanged();
}

void RTextDocument::Save()
{
    SFileUtils::SaveTo(PieceTable.GetText(), FilePath);
    PieceTable.NotifyDocumentSaved();
}

void RTextDocument::Undo(SDocumentPosition& InOutCursorPos)
{
    PieceTable.Undo(InOutCursorPos);
}

void RTextDocument::Redo(SDocumentPosition& InOutCursorPos)
{
    PieceTable.Redo(InOutCursorPos);
}

bool RTextDocument::CanUndo() const
{
    return PieceTable.CanUndo();
}

bool RTextDocument::CanRedo() const
{
    return PieceTable.CanRedo();
}

void RTextDocument::InitPieceTable()
{
    CString FileContent = SFileUtils::ReadToString(FilePath);
    if(FileContent.IsEmpty())
    {
        PieceTable.Buffers.Resize(1);
        PieceTable.Buffers[0].Text.Clear();
        return ;
    }

    PieceTable.Buffers.Resize(1);
    PieceTable.Buffers[0].Text = FileContent;
    //fill line starts
    PieceTable.Buffers[0].LineStarts.Add(0);
    int64_t LineFeedCount = 0;
    for (int64_t i = 0; i < PieceTable.Buffers[0].Text.GetLength(); i++)
    {
        if (PieceTable.Buffers[0].Text[i] == '\n')
        {
            LineFeedCount++;
            if((i+1)<PieceTable.Buffers[0].Text.GetLength())
            {
                PieceTable.Buffers[0].LineStarts.Add(i + 1);
            }
        }
    }


    PieceTable.Nodes.Resize(1);
    PieceTable.Nodes[0].BufferIndex = 0;
    PieceTable.Nodes[0].Start.LineIndex = 0;
    PieceTable.Nodes[0].Start.ColumnIndex = 0;
    PieceTable.Nodes[0].End.LineIndex = PieceTable.Buffers[0].LineStarts.Num() - 1;
    PieceTable.Nodes[0].End.ColumnIndex = 
        PieceTable.Buffers[0].Text.GetLength()-1
        -PieceTable.Buffers[0].LineStarts.Last();
        ;
    PieceTable.Nodes[0].Length = PieceTable.Buffers[0].Text.GetLength();
    PieceTable.Nodes[0].LineFeedCount = LineFeedCount;

    // PieceTable.CursorPosition.Position.LineIndex = 0;
    // PieceTable.CursorPosition.Position.ColumnIndex = 0;    

}
